package com.woniu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.client.AccountClient;
import com.woniu.client.ProductClient;
import com.woniu.commons.exception.YogaException;
import com.woniu.commons.model.StateData;
import com.woniu.dao.mapper.YPersonalDetailMapper;
import com.woniu.model.UserAndClassIdForm;
import com.woniu.model.YClassTypeDto;
import com.woniu.model.YPersonalClass;
import com.woniu.model.YUserPersonalClassMargin;
import com.woniu.model.dto.UserByMyPersonalDetailDto;
import com.woniu.model.dto.UserPersonalClassMarginDto;
import com.woniu.model.model.YPersonalDetail;
import com.woniu.model.param.AddPersonalClassDetailParam;
import com.woniu.service.YPersonalDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 胡歌
 * @since 2024年05月28日
 */
@Service
public class YPersonalDetailServiceImpl extends ServiceImpl<YPersonalDetailMapper, YPersonalDetail> implements YPersonalDetailService {

    @Resource
    private ProductClient productClient;
    @Resource
    private AccountClient accountClient;
    @Override
    public void addPersonalClassDetail(AddPersonalClassDetailParam param) {
        QueryWrapper<YPersonalDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("coach_id",param.getCoachId()).eq("personal_class_state", 2);//未完成
        wrapper.lt("start_time",param.getEndTime()).gt("end_time",param.getEndTime());

        wrapper.or();
        wrapper.eq("coach_id",param.getCoachId()).eq("personal_class_state", 2);
        wrapper.gt("end_time",param.getStartTime()).lt("start_time",param.getStartTime());

        wrapper.or();
        wrapper.eq("coach_id",param.getCoachId()).eq("personal_class_state", 2);
        wrapper.lt("end_time",param.getStartTime()).gt("start_time",param.getStartTime());

        List<YPersonalDetail> list = baseMapper.selectList(wrapper);
        if (list.size()!=0){
            throw new YogaException(3301,"该时间段教练已有课程");
        }

        YUserPersonalClassMargin margin = productClient.loadPersonalMarginByUserAndClassId(new UserAndClassIdForm(param.getUserId(), param.getCoachId())).getData();
        System.out.println(margin);

        if (margin.getMarginNum()==0){
            throw new YogaException(3303,"用户课程余量不足");
        }
        YPersonalDetail personalDetail = BeanUtil.toBean(param, YPersonalDetail.class);
        personalDetail.setUserPersonalClassMarginId(margin.getId());
        personalDetail.setPersonalClassId(margin.getPersonalClassId());
        personalDetail.setPersonalClassState(StateData.PERSONAL_CLASS_STATE_NOT_OK);
        baseMapper.insert(personalDetail);

    }

    @Override
    @GlobalTransactional(rollbackFor = Throwable.class)
    public void finishPersonalClassDetail(Integer id, Integer coachId) {
        YPersonalDetail personalDetail = baseMapper.selectById(id);
        if (personalDetail == null){
            throw new YogaException(3304,"该私教课详情不存在");
        }
        if (!personalDetail.getCoachId().equals(coachId)){
            throw new YogaException(3305,"教练无此权限");
        }
        personalDetail.setPersonalClassState(StateData.PERSONAL_CLASS_STATE_FINISH);

        productClient.substractPersonalMarginByUserAndClassId(personalDetail.getUserPersonalClassMarginId());

        baseMapper.updateById(personalDetail);
    }

    @Override
    public void cancelPersonalClassDetail(Integer id) {
        YPersonalDetail personalDetail = baseMapper.selectById(id);
        if (personalDetail == null){
            throw new YogaException(3310,"该课程详情不存在");
        }
        personalDetail.setPersonalClassState(StateData.PERSONAL_CLASS_STATE_CANCEL);
        baseMapper.updateById(personalDetail);
    }

    @Override
    public List<UserPersonalClassMarginDto> loadPersonalClassByCoachId(Integer coachId) {
        List<YPersonalDetail> margins = baseMapper.selectList(new QueryWrapper<YPersonalDetail>().eq("personal_class_state", StateData.PERSONAL_CLASS_STATE_NOT_OK).eq("coach_id", coachId));

        ArrayList<UserPersonalClassMarginDto> dtos = new ArrayList<>();
        for (YPersonalDetail m:margins
        ) {
            UserPersonalClassMarginDto d = new UserPersonalClassMarginDto();
            d.setDetail(m);
            d.setUserNickname(accountClient.loadUsersByIds(m.getUserId()).getData().getUserNickname());
            dtos.add(d);
        }
        return dtos;
    }

    /**
     * 通过用户token查该用户的私课细节（上课时间）
     * @param
     * @return
     */
    @Override
    public UserByMyPersonalDetailDto userByMyPersonalDetail(Integer userId) {

        QueryWrapper<YPersonalDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<YPersonalDetail> list = baseMapper.selectList(wrapper);

        List<Integer> ids = list.stream().map(YPersonalDetail::getId).collect(Collectors.toList());
        List<LocalDateTime> startTimes = list.stream().map(YPersonalDetail::getStartTime).collect(Collectors.toList());
        List<LocalDateTime> endTimes = list.stream().map(YPersonalDetail::getEndTime).collect(Collectors.toList());
        List<Integer> coachIds = list.stream().map(YPersonalDetail::getCoachId).collect(Collectors.toList());
        List<Integer> userPersonalClassMarginIds = list.stream().map(YPersonalDetail::getUserPersonalClassMarginId).collect(Collectors.toList());
        List<Integer> personalClassIds = list.stream().map(YPersonalDetail::getPersonalClassId).collect(Collectors.toList());

        System.out.println(ids);
        System.out.println(startTimes);
        System.out.println(endTimes);
        System.out.println(coachIds);
        System.out.println(userPersonalClassMarginIds);
        System.out.println(personalClassIds);

        UserByMyPersonalDetailDto dto = new UserByMyPersonalDetailDto();

        for (Integer id:ids){
            dto.setId(id);
        }
        for (LocalDateTime startTime:startTimes){
            dto.setStartTime(startTime);
        }
        for (LocalDateTime endTime:endTimes){
            dto.setEndTime(endTime);
        }
        for (Integer coachId:coachIds){

            dto.setCoachId(coachId);

            String coachName = accountClient.byCoachId(coachId).getData().getCoachName();
            dto.setCoachName(coachName);

        }
        for (Integer userPersonalClassMarginId: userPersonalClassMarginIds){
            dto.setUserPersonalClassMarginId(userPersonalClassMarginId);
        }
        for (Integer personalClassId:personalClassIds ){
            dto.setPersonalClassId(personalClassId);

            YPersonalClass yPersonalClass = productClient.byIdPersonal(personalClassId).getData();
            dto.setPrice(yPersonalClass.getPrice());
            dto.setMinute(yPersonalClass.getMinute());
            dto.setScore(yPersonalClass.getScore());
            dto.setPersonalClassState(yPersonalClass.getPersonalClassState());

            YClassTypeDto yClassTypeDto = productClient.byClassTypeId(yPersonalClass.getClassTypeId()).getData();
            System.out.println(yClassTypeDto);
            dto.setClassTypeId(yPersonalClass.getClassTypeId());
            dto.setClassTypeName(yClassTypeDto.getClassTypeName());

        }
        dto.setUserId(userId);

        return dto;
    }








}
